package com.hisense.hiioc.hismartplate.controller;

import com.hisense.hiioc.hismartplate.constants.URLConstant;
import com.hisense.hiioc.hismartplate.entity.response.BaseRes;
import com.hisense.hiioc.hismartplate.service.DeviceLogService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;

/**
 * @Auther:biexiande@hisense.com
 * @date:2019/3/1 11:08
 * @des 访问日志接口
 */
@RestController
@RequestMapping(URLConstant.AccessLogURLMapping.BASE_URL)
public class AccessLogController  {
    public static final Logger LOGGER = LoggerFactory.getLogger(AccessLogController.class);
    @Autowired
    TaskExecutor taskExecutor;

    @Autowired
    DeviceLogService deviceLogService;
    //@Autowired
    //RabbitSender rabbitSender;

    @ApiOperation(value = "上传设备的应用访问信息")
    @PostMapping("/uploadLogFile")
    public BaseRes uplogfile(@RequestParam(value = "file",required=false) MultipartFile[] files) throws Exception{
        StringBuffer filestring=new StringBuffer();
        for(MultipartFile file :files) {
            String ret = new String(file.getBytes(), "UTF-8").substring(0);
            filestring.append(ret);
        }
        System.out.println("fileName：" + files[0].getOriginalFilename());
        String path="/tmp/logfile/"+new Date().getTime()+files[0].getOriginalFilename();
        File newFile=new File(path);
        files[0].transferTo(newFile);

        LOGGER.debug(filestring.toString());
        taskExecutor.execute(()->deviceLogService.processLog(filestring.toString()));
        BaseRes<String> res = new BaseRes<>();
        res.setErr_no(HttpStatus.OK.value());
        res.setErr_msg("success");
        res.setSST(filestring.toString());
        return res;
    }
}